<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="row.publish_status ? 'success' : 'info'"
            >{{
              row.publish_status === 1
                ? t("material.status.up")
                : t("material.status.down")
            }}
          </el-tag>
        </template>
        <template #overdue_time_default="{ row }">
          <!--          <el-tag :type="row.overdue_time ? 'primary' : 'info'"-->
          <!--            >-->
          <!--          </el-tag>-->
          {{ row.overdue_time / 3600000 }}
        </template>
        <template #clean_time_default="{ row }">
          <!--          <el-tag :type="row.clean_time ? 'primary' : 'info'"-->
          <!--            >-->
          <!--          </el-tag>-->
          {{ Number(row.clean_time / 86400000).toFixed(0) }}
        </template>
      </AuTable>
    </div>

    <MtrlModal
      v-model="showModal"
      :rowData="rowData"
      :activeType="activeType"
      :lastMatRow="lastMatRow"
      @handleConfirm="handleConfirm"
    />

    <UploadModal v-model="showUploadModal" @handleConfirm="handleConfirm" />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { materialTypeSelectForMaterial } from "@/utils/formSelect";
import { getMaterialList, MaterialListProp } from "@/api/cabinet/formula";
import { saveAs } from "file-saver";

import {
  materialDelete,
  MaterialProp,
  materialPublish
} from "@/api/cabinet/material";
import MtrlModal from "./MtrlModal.vue";
import { VxeUI } from "vxe-table";
import { ElMessage } from "element-plus";
import UploadModal from "./uploadModal.vue";

defineOptions({
  name: "FormulaMaterialManage"
});
import { useI18n } from "vue-i18n";
import { getFormulaList } from "@/api/teaInfuser/formula";
import ExcelJS from "exceljs";

const { proxy } = getCurrentInstance();
const { t } = useI18n();

// region 声明ref变量集合
const formList = ref([
  {
    type: "select",
    key: "publish_status",
    label: "material.form.status",
    placeholder: "material.form.status_placeholder",
    valueKey: "value",
    labelKey: "label",
    emptyValues: [null, undefined],
    options: [
      { value: "", label: "material.form.status_all" },
      { value: 1, label: "material.status.up" },
      { value: 0, label: "material.status.down" }
    ],
    defaultValue: ""
  },
  materialTypeSelectForMaterial,
  {
    type: "input",
    key: "material_id",
    label: "material.form.material_id",
    placeholder: "material.form.material_id_placeholder"
  },
  {
    type: "input",
    key: "name",
    label: "material.form.name",
    placeholder: "material.form.name_placeholder"
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    {
      field: "material_id",
      title: "material.table.material_id",
      minWidth: 145,
      align: "center"
    },
    {
      field: "name",
      title: "material.table.name",
      minWidth: 160,
      align: "center"
    },
    {
      field: "type_name",
      title: "material.table.type",
      minWidth: 100,
      align: "center"
    },
    {
      field: "publish_status",
      title: "material.table.status",
      width: 100,
      slots: {
        default: "status_default"
      },
      align: "center"
    },
    // {
    //   field: "overdue_time",
    //   title: "保质期/时",
    //   minWidth: 125,
    //   align: "center",
    //   slots: {
    //     default: "overdue_time_default"
    //   }
    // },
    /* {field: 'cold_time', title: '冷藏保质期/时', minWidth: 125, align: 'center'}, */
    /* {field: 'standard_amount', title: '标准量', minWidth: 100, align: 'center'}, */
    {
      field: "amount_unit",
      title: "material.table.amount_unit",
      minWidth: 100,
      align: "center"
    },
    // {
    //   field: "clean_time",
    //   title: "清洗周期/天",
    //   minWidth: 125,
    //   align: "center",
    //   slots: {
    //     default: "clean_time_default"
    //   }
    // },
    /* {title: '清洗类型', templet: '#listData-material_config', minWidth: 100, align: 'center'}, */
    {
      field: "barcode",
      title: "material.table.barcode",
      minWidth: 100,
      align: "center"
    },
    {
      field: "note",
      title: "table.note",
      minWidth: 145,
      align: "center"
    },
    {
      field: "create_time",
      title: "material.table.create_time",
      width: 170,
      align: "center"
    }
  ],
  actions: [
    ACTION_TYPE.TADD,
    ACTION_TYPE.TDELETE,
    ACTION_TYPE.TPUTAWAY,
    ACTION_TYPE.TOFFSHELVE,
    ACTION_TYPE.EDIT,
    ACTION_TYPE.UPLOAD,
    ACTION_TYPE.DOWNLOAD
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        return getMaterialList(params);
      },
      param: () => formRef.value.getFormData()
    }
  }
});

const showModal = ref(false);
const showUploadModal = ref(false);
const rowData = ref();
const lastMatRow = ref([]);
const activeType = ref();
const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合

// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

type ActionType = {
  key: ACTION_TYPE;
  row: MaterialListProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.EDIT:
      activeType.value = ACTION_TYPE.EDIT;
      initMaterial(row);
      showModal.value = true;
      break;
    case ACTION_TYPE.TADD:
      activeType.value = ACTION_TYPE.TADD;
      rowData.value = null;
      const $table = tableRef.value.vxeGridRef;
      console.log($table);
      const list = $table.getTableData().fullData;
      lastMatRow.value = list;
      showModal.value = true;
      break;
    case ACTION_TYPE.UPLOAD:
      showUploadModal.value = true;
      break;
    case ACTION_TYPE.DOWNLOAD:
      exportExcel();
      break;
    case ACTION_TYPE.TPUTAWAY:
      const onKey = ACTION_TYPE.TPUTAWAY;
      const onList = tableRef.value.getCheckboxRecords();

      handleUpOrDown(onList, onKey);
      break;
    case ACTION_TYPE.TOFFSHELVE:
      const offKey = ACTION_TYPE.TOFFSHELVE;
      const offList = tableRef.value.getCheckboxRecords();

      handleUpOrDown(offList, offKey);
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(t("material.message.confirm_delete"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checkedNodes = tableRef.value.getCheckboxRecords();
          console.log(checkedNodes);
          if (checkedNodes.length > 0) {
            //const ids = checkedNodes.map(item => ({ id: item.id }));
            materialDelete({
              materialList: JSON.stringify(checkedNodes)
            }).then(res => {
              if (res.code === 200) {
                VxeUI.modal.message({
                  content: t("notice.operation_success"),
                  status: "success"
                });
                tableRef.value.refresh();
                //getMaterialListData();
              }
            });
          }
        })
        .catch(() => {});
      break;
  }
};

async function getMaterialListData() {
  const params = {
    start_page: 1,
    size: 0,
    ...formRef.value.getFormData()
  };
  const res = await getMaterialList(params);
  gridOption.dataSource = res.data;
}

const handleUpOrDown = (
  rows: MaterialProp[],
  status: ACTION_TYPE.TOFFSHELVE | ACTION_TYPE.TPUTAWAY
) => {
  const name = rows.map(v => v.name);
  /* const ids = [];
  for (let i = 0; i < rows.length; i++) {
    ids.push({ id: rows[i].id });
  } */

  const statusText =
    status === ACTION_TYPE.TOFFSHELVE
      ? t("material.status.down")
      : t("material.status.up");
  const msg = t("material.message.confirm_status_change", {
    name: name.join("、"),
    status: statusText
  });

  proxy.$auMessageBox.confirm(msg, t("notice.title")).then(() => {
    const param = {
      publish_status: status === ACTION_TYPE.TOFFSHELVE ? 0 : 1,
      materialList: JSON.stringify(rows)
    };
    materialPublish(param).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: t("material.message.status_change_success", {
            status: statusText
          }),
          type: "success"
        });
        tableRef.value.refresh();
        //getMaterialListData();
      }
    });
  });
};

const handleConfirm = () => {
  showModal.value = false;
  tableRef.value.refresh();
};

//为修改组织数据
const initMaterial = (row: MaterialListProp) => {
  const spec = ref();

  if (row.spec != null && isValidJSON(row.spec)) {
    spec.value = JSON.parse(row.spec);
  }
  const forced_clean = ref(false);

  if (row.material_config != null && isValidJSON(row.material_config)) {
    forced_clean.value = JSON.parse(row.material_config).forced_clean;
  }

  const material = ref({
    id: row.id,
    material_id: row.material_id,
    name: row.name,
    type_id: row.type_id,
    overdue_time_input: Number(row.overdue_time) / 3600000,
    cold_time_input: Number(row.cold_time) / 3600000,
    amount_unit: row.amount_unit,
    clean_time_input: Number(row.clean_time) / 86400000,
    use_barcode: row.use_barcode,
    barcode: row.barcode,
    publish_status: row.publish_status,
    spec: spec.value,
    forced_clean: forced_clean.value,
    device_type: row.device_type,
    note: row.note
  });

  console.log(material.value);
  rowData.value = material.value;

  //formRef.value.setFormData(material.value); //赋值
};

// 基础判断方法
const isValidJSON = text => {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
};

// 导出
const exportExcel = async () => {
  console.log("开始导出配方");

  //获取配方列表
  const hxtFormulaParam = formRef.value.getFormData();

  const params = {
    start_page: 1,
    size: 0,
    ...hxtFormulaParam
  };

  let pfResult = await getMaterialList(params); //获取配方列表
  if (pfResult.code == 200 && pfResult.data.length > 0) {
    const pfList = pfResult.data;
    // 获取模板文件
    const response = await fetch("/admin/物料管理.xlsx");
    const arrayBuffer = await response.arrayBuffer();

    // 创建工作簿
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(arrayBuffer);

    // 获取第一个工作表
    const worksheet = workbook.getWorksheet(1);

    const matKeyList = [
      "material_id",
      "name",
      "type_name",
      "publish_status",
      "device_type",
      "spec",
      "use_barcode",
      "barcode",
      "note"
    ];

    for (let i = 0; i < pfList.length; i++) {
      const item = pfList[i];
      for (let j = 0; j < matKeyList.length; j++) {
        const key = matKeyList[j];
        let value = item[key];
        if (key === "publish_status") {
          value = value === 1 ? "上架" : "下架";
        } else if (key === "spec") {
          const spec = JSON.parse(value);
          let str = "";
          for (let k = 0; k < spec.length; k++) {
            const specItem = spec[k];
            str += specItem.name + "-" + specItem.value;
            if (k !== spec.length - 1) {
              str += ",";
            }
          }
          value = str;
        } else if (key === "use_barcode") {
          value = value ? "是" : "否";
        }
        worksheet.getRow(i + 2).getCell(j + 1).value = value;
      }
    }

    workbook.xlsx.writeBuffer().then(function (buffer) {
      // 生成excel文件的二进制数据
      saveAs.saveAs(
        new Blob([buffer], {
          // 生成Blob对象
          type: "application/octet-stream" // 指定文件的MIME类型
        }),
        `${t("menus.materialData")}.xlsx`
      ); // 指定文件名
    });
  } else {
    ElMessage({
      message: t("material.no_export_data"),
      type: "warning"
    });
  }
};
// endregion
</script>
